package com.feel.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.feel.exception.SteduException;
import com.feel.pojo.RespBean;
import com.feel.pojo.User;
import com.feel.service.UserService;
import com.feel.utils.RedisUtil;
import com.feel.utils.ThreadLocalUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: 刘永钦
 * @Date: 2024-09-03-9:37
 * @Description:
 */
@RestController
public class UserController {
    // 缓存文件
    //TimedCache<String, String> localCache = CacheUtil.newTimedCache(300000);
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;

    /**
     * 登录接口
     */
    @PostMapping("/login")
    RespBean login(@NotNull String username, @NotNull String password , @NotNull String captcha, @NotNull String uuid) throws SteduException {
        //获取缓存中的验证码
        //String cacheCaptcha = localCache.get(uuid);
        // 获取redis中的数据
        String  str = (String) redisUtil.get(uuid);

        //效验成功
        if(str == null || !captcha.equalsIgnoreCase(str)){
            throw new SteduException("验证码错误");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        String token = userService.login(user);

        return RespBean.ok("登录成功", token);
    }

    /**
     * 获得验证码
     * @throws IOException
     */
    @GetMapping("/captcha")
    public RespBean captcha() throws IOException {
        //生成验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 20);
        // 生成UUID --雪花算法生成
        String uuid = IdUtil.getSnowflakeNextIdStr();

        // 放入redis
        redisUtil.set(uuid, captcha.getCode(), 60);

        HashMap<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("captcha", captcha.getImageBase64Data());

        return RespBean.ok("",map);
        //保存到缓存
        //localCache.put(uuid, captcha.getCode());
        //返回验证码图片给浏览器
        //captcha.write(response.getOutputStream());
    }
    /**
     * 删除用户接口
     */
    @DeleteMapping("/admin/user/{id}")
    RespBean delUser(@PathVariable("id") @NotNull Integer userId) throws SteduException {
        Boolean b = userService.delUser(userId);
        return b ? RespBean.ok("删除成功") : RespBean.error("删除失败");
    }

    /**
     * 修改用户基本信息
     */
    @PutMapping("/admin/user")
    RespBean updateUser(@RequestBody @Validated User user) throws SteduException {
        Boolean b = userService.updateUser(user);
        return b ? RespBean.ok("修改成功") : RespBean.error("修改失败");
    }
    /**
     * 新增员工
     */
    @PostMapping("/admin/user")
    RespBean addUser(@RequestBody User user) throws SteduException {
        user.setRole("emp");
        user.setPassword(SecureUtil.md5("123"));
        Boolean b = userService.addUser(user);
        return b ? RespBean.ok("新增成功") : RespBean.error("新增失败");
    }
    /**
     * 获得用户列表
     */
    @GetMapping("/admin/user")
    RespBean getAll(String role, Integer currentPage, String name) throws SteduException {
        // todo 显现分页，按角色查询
        if (StrUtil.hasEmpty(name)) {
            name = null;
        }
        PageInfo<User> list = userService.getAll(currentPage, role, name);
        return RespBean.ok("查询成功", list);
    }
    /**
     * 获得部门员工列表，实现分类
     */
    @GetMapping("/admin/user/list")
    RespBean getList(Integer did) throws SteduException {
        List<User> list = userService.getList(did);
        return RespBean.ok("查询成功", list);
    }

    /**
     * 获得用户列表
     */
    @GetMapping("/admin/user/userList")
    RespBean getUserList() throws SteduException {
        List<User> list = userService.getList(0);
        return RespBean.ok("查询成功", list);
    }

    /**
     * 通过id查询用户
     */
    @GetMapping("/admin/user/{id}")
    RespBean getById(@PathVariable("id") Integer id) {
        if(id <= 0) {
            id =(Integer) ThreadLocalUtil.get();
        }
        User user = userService.getById(id);
        return RespBean.ok("查询成功", user);
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/admin/user/password")
    RespBean updatePassword(@NotNull String oldPassword,@NotNull String password, @NotNull String rpassword) throws SteduException {
        Integer id = ThreadLocalUtil.get();
        User login = userService.getById(id);
        if (!SecureUtil.md5(oldPassword).equals(login.getPassword())) {
            throw new SteduException("密码错误");
        }
        if (StrUtil.hasEmpty(password) || StrUtil.hasEmpty(rpassword)) {
            throw  new SteduException("密码不能为空");
        }
        if (!password.equals(rpassword)) {
            throw new SteduException("两次密码不同");
        }
        String md5 = SecureUtil.md5(password);
    //
    //    本地线程获取用户id    上边已经获取

    //    生成用户对象
        User user = new User();
        //
        user.setUserId(id);
        user.setPassword(md5);

        Boolean b = userService.updateUser(user);
        return b ? RespBean.ok("更新成功") : RespBean.error("更新失败");
    }
    /**
     * 新增普通用户       没有限制，不需要进行登录验证
     */
    @PostMapping("/addUser")
    RespBean addUserP(@RequestBody User user) throws SteduException {
        user.setRole("user");
        user.setPassword(SecureUtil.md5("123"));
        Boolean b = userService.addUser(user);
        return b ? RespBean.ok("新增成功") : RespBean.error("新增失败");
    }
}
